<template>
  <div class="xgplayer-container">
    <div ref="playerContainer" class="player-wrapper"></div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onBeforeUnmount,
  watch,
  defineProps,
  defineEmits,
  defineExpose,
  nextTick,
} from "vue";
import Player from "xgplayer";
import "xgplayer/dist/index.min.css";

// 组件属性
const props = defineProps({
  // 视频流地址
  url: {
    type: String,
    required: true,
    default: "",
  },
  // 播放器配置
  config: {
    type: Object,
    default: () => ({}),
  },
  // 是否自动播放
  autoplay: {
    type: Boolean,
    default: false,
  },
  // 播放器宽度
  width: {
    type: [String, Number],
    default: "100%",
  },
  // 播放器高度
  height: {
    type: [String, Number],
    default: "100%",
  },
  // 是否显示控制栏
  controls: {
    type: Boolean,
    default: true,
  },
  // 是否静音
  muted: {
    type: Boolean,
    default: false,
  },
  // 封面图片
  poster: {
    type: String,
    default: "",
  },
  // 是否流式播放
  fluid: {
    type: Boolean,
    default: true,
  },
});

// 组件事件
const emit = defineEmits([
  "ready",
  "play",
  "pause",
  "ended",
  "error",
  "loadstart",
  "canplay",
  "timeupdate",
  "volumechange",
  "seeking",
  "seeked",
  "waiting",
  "loadeddata",
]);

// 响应式数据
const playerContainer = ref(null);
let player = null;

// 根据URL判断视频格式类型
const getVideoType = (url) => {
  if (!url) return "mp4";

  const lowerUrl = url.toLowerCase();

  if (lowerUrl.includes(".m3u8") || lowerUrl.includes("hls")) {
    return "hls";
  } else if (lowerUrl.includes(".flv") || lowerUrl.includes("flv")) {
    return "flv";
  } else {
    return "mp4";
  }
};

// 动态加载插件
const loadPlugins = async (type) => {
  const plugins = [];

  try {
    switch (type) {
      case "hls":
        try {
          // 尝试加载 HLS 插件
          const { default: HlsPlugin } = await import("xgplayer-hls");
          plugins.push(HlsPlugin);
        } catch (error) {
          console.warn("HLS 插件加载失败，使用原生 HLS 支持:", error);
        }
        break;
      case "flv":
        try {
          // 尝试加载 FLV 插件
          const { default: FlvPlugin } = await import("xgplayer-flv");
          plugins.push(FlvPlugin);
        } catch (error) {
          console.warn("FLV 插件加载失败:", error);
        }
        break;
      default:
        // mp4格式使用默认播放器，不需要额外插件
        break;
    }
  } catch (error) {
    console.warn("插件加载过程中出现错误:", error);
  }

  return plugins;
};

// 初始化播放器
const initPlayer = async () => {
  if (!props.url || !playerContainer.value) {
    console.warn("播放器初始化失败：缺少URL或DOM容器");
    return;
  }

  const videoType = getVideoType(props.url);
  const plugins = await loadPlugins(videoType);

  console.log("检测到视频格式:", videoType);
  console.log("加载的插件数量:", plugins.length);

  // 播放器基础配置
  const playerConfig = {
    el: playerContainer.value,
    url: props.url,
    autoplay: props.autoplay,
    width: props.width,
    height: props.height,
    poster: props.poster,
    playsinline: true,
    controls: props.controls,
    fluid: props.fluid,
    muted: props.muted,
    // 基本配置
    lang: "zh-cn",
    // 预加载配置
    preload: "auto",
    // 音量配置
    volume: props.muted ? 0 : 0.6,
    // 播放速率选项
    playbackRate: [0.5, 0.75, 1, 1.25, 1.5, 2],
    // 合并用户自定义配置
    ...props.config,
  };

  // 如果有插件，添加到配置中
  if (plugins.length > 0) {
    playerConfig.plugins = plugins;
  }

  console.log("播放器配置:", playerConfig);

  try {
    player = new Player(playerConfig);

    // 绑定事件监听
    bindEvents();

    console.log(`XGPlayer 初始化成功，格式：${videoType}`);
  } catch (error) {
    console.error("播放器初始化失败:", error);
    emit("error", error);
  }
};

// 绑定播放器事件
const bindEvents = () => {
  if (!player) return;

  // 基础事件
  player.on("ready", () => {
    console.log("播放器准备就绪");
    emit("ready", player);
  });

  player.on("play", () => {
    console.log("开始播放");
    emit("play");
  });

  player.on("pause", () => {
    console.log("暂停播放");
    emit("pause");
  });

  player.on("ended", () => {
    console.log("播放结束");
    emit("ended");
  });

  player.on("error", (error) => {
    console.error("播放器错误:", error);
    emit("error", error);
  });

  player.on("loadstart", () => {
    console.log("开始加载");
    emit("loadstart");
  });

  player.on("canplay", () => {
    console.log("可以播放");
    emit("canplay");
  });

  // 扩展事件
  player.on("timeupdate", () => {
    emit("timeupdate", {
      currentTime: player.currentTime,
      duration: player.duration,
    });
  });

  player.on("volumechange", () => {
    emit("volumechange", {
      volume: player.volume,
      muted: player.muted,
    });
  });

  player.on("seeking", () => {
    emit("seeking", player.currentTime);
  });

  player.on("seeked", () => {
    emit("seeked", player.currentTime);
  });

  player.on("waiting", () => {
    emit("waiting");
  });

  player.on("loadeddata", () => {
    emit("loadeddata", {
      duration: player.duration,
      videoWidth: player.videoWidth,
      videoHeight: player.videoHeight,
    });
  });
};

// 播放
const play = () => {
  if (player && typeof player.play === "function") {
    return player.play();
  }
};

// 暂停
const pause = () => {
  if (player && typeof player.pause === "function") {
    player.pause();
  }
};

// 跳转到指定时间
const seek = (time) => {
  if (player && typeof player.seek === "function") {
    player.seek(time);
  } else if (player) {
    player.currentTime = time;
  }
};

// 设置音量
const setVolume = (volume) => {
  if (player) {
    player.volume = Math.max(0, Math.min(1, volume));
  }
};

// 设置静音
const setMuted = (muted) => {
  if (player) {
    player.muted = muted;
  }
};

// 设置播放速率
const setPlaybackRate = (rate) => {
  if (player) {
    player.playbackRate = rate;
  }
};

// 全屏
const requestFullscreen = () => {
  if (player && typeof player.getFullscreen === "function") {
    player.getFullscreen();
  }
};

// 退出全屏
const exitFullscreen = () => {
  if (player && typeof player.exitFullscreen === "function") {
    player.exitFullscreen();
  }
};

// 重新加载
const reload = () => {
  if (player) {
    const currentTime = player.currentTime || 0;
    try {
      player.src = props.url;
      if (typeof player.load === "function") {
        player.load();
      }
      // 尝试恢复到之前的播放位置
      setTimeout(() => {
        if (currentTime > 0) {
          seek(currentTime);
        }
      }, 1000);
    } catch (error) {
      console.error("重新加载失败:", error);
    }
  }
};

// 切换播放/暂停
const toggle = () => {
  if (player) {
    if (player.paused) {
      play();
    } else {
      pause();
    }
  }
};

// 销毁播放器
const destroyPlayer = () => {
  if (player) {
    try {
      player.destroy();
      player = null;
      console.log("XGPlayer V2 播放器已销毁");
    } catch (error) {
      console.error("销毁播放器失败:", error);
    }
  }
};

// 获取播放器实例
const getPlayer = () => {
  return player;
};

// 获取播放器状态
const getPlayerState = () => {
  if (!player) return null;

  return {
    currentTime: player.currentTime || 0,
    duration: player.duration || 0,
    volume: player.volume || 0,
    muted: player.muted || false,
    paused: player.paused !== false,
    ended: player.ended || false,
    playbackRate: player.playbackRate || 1,
    buffered: player.buffered || null,
    videoWidth: player.videoWidth || 0,
    videoHeight: player.videoHeight || 0,
  };
};

// 监听URL变化，重新初始化播放器
watch(
  () => props.url,
  async (newUrl, oldUrl) => {
    if (newUrl !== oldUrl) {
      destroyPlayer();
      if (newUrl && playerContainer.value) {
        await nextTick();
        await initPlayer();
      }
    }
  }
);

// 监听其他配置变化
watch(
  () => [props.autoplay, props.muted, props.controls],
  () => {
    if (player) {
      // 如果播放器已存在，直接更新配置
      if (typeof props.autoplay !== "undefined") {
        player.autoplay = props.autoplay;
      }
      if (typeof props.muted !== "undefined") {
        player.muted = props.muted;
      }
    }
  },
  { deep: true }
);

// 生命周期钩子
onMounted(async () => {
  await nextTick();
  // 确保DOM和props都准备就绪
  if (playerContainer.value && props.url) {
    await initPlayer();
  } else if (props.url) {
    // 如果URL存在但DOM还没准备好，稍后重试
    setTimeout(async () => {
      if (playerContainer.value && props.url) {
        await initPlayer();
      }
    }, 100);
  }
});

onBeforeUnmount(() => {
  destroyPlayer();
});

// 对外暴露的方法
defineExpose({
  // 基础控制方法
  play,
  pause,
  toggle,
  seek,
  reload,
  destroyPlayer,

  // 音量控制
  setVolume,
  setMuted,

  // 播放速率
  setPlaybackRate,

  // 全屏控制
  requestFullscreen,
  exitFullscreen,

  // 获取信息
  getPlayer,
  getPlayerState,
});
</script>

<style scoped>
.xgplayer-container {
  width: 100%;
  height: 100%;
  position: relative;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.player-wrapper {
  width: 100%;
  height: 100%;
  background: #000;
  position: relative;
}

/* XGPlayer V2 自定义样式 */
:deep(.xgplayer) {
  font-family: "PingFang SC", "Microsoft YaHei", "Helvetica Neue", Arial,
    sans-serif;
  width: 100% !important;
  height: 100% !important;
  border-radius: 8px;
  overflow: hidden;
}

/* 控制栏样式 */
:deep(.xgplayer-controls) {
  background: linear-gradient(
    to top,
    rgba(0, 0, 0, 0.8) 0%,
    rgba(0, 0, 0, 0.4) 50%,
    transparent 100%
  );
  backdrop-filter: blur(4px);
}

/* 播放按钮 */
:deep(.xgplayer-play) {
  color: #fff;
  transition: all 0.3s ease;
}

:deep(.xgplayer-play:hover) {
  color: #409eff;
  transform: scale(1.1);
}

/* 时间显示 */
:deep(.xgplayer-time) {
  color: #fff;
  font-size: 13px;
  font-weight: 500;
}

/* 进度条 */
:deep(.xgplayer-progress) {
  height: 6px;
  border-radius: 3px;
  background: rgba(255, 255, 255, 0.3);
}

:deep(.xgplayer-progress-played) {
  background: linear-gradient(90deg, #409eff 0%, #66b3ff 100%);
  border-radius: 3px;
}

:deep(.xgplayer-progress-buffered) {
  background: rgba(255, 255, 255, 0.4);
  border-radius: 3px;
}

:deep(.xgplayer-progress-dot) {
  width: 14px;
  height: 14px;
  background: #409eff;
  border: 2px solid #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

/* 音量控制 */
:deep(.xgplayer-volume) {
  color: #fff;
  transition: all 0.3s ease;
}

:deep(.xgplayer-volume:hover) {
  color: #409eff;
}

/* 全屏按钮 */
:deep(.xgplayer-fullscreen) {
  color: #fff;
  transition: all 0.3s ease;
}

:deep(.xgplayer-fullscreen:hover) {
  color: #409eff;
  transform: scale(1.1);
}

/* 设置按钮 */
:deep(.xgplayer-setting) {
  color: #fff;
  transition: all 0.3s ease;
}

:deep(.xgplayer-setting:hover) {
  color: #409eff;
}

/* 加载动画 */
:deep(.xgplayer-loading) {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(4px);
}

:deep(.xgplayer-loading .xgplayer-loading-rotate) {
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #409eff;
}

/* 播放器遮罩 */
:deep(.xgplayer-mask) {
  background: rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
}

/* 中央播放按钮 */
:deep(.xgplayer-start) {
  width: 80px;
  height: 80px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 50%;
  backdrop-filter: blur(4px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

:deep(.xgplayer-start:hover) {
  background: rgba(64, 158, 255, 0.9);
  border-color: #409eff;
  transform: scale(1.1);
}

:deep(.xgplayer-start .xgplayer-start-img) {
  width: 32px;
  height: 32px;
  filter: brightness(0) invert(1);
}

/* 音量滑块 */
:deep(.xgplayer-volume-panel) {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(8px);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

/* 设置面板 */
:deep(.xgplayer-setting-panel) {
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(8px);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #fff;
}

/* 错误提示 */
:deep(.xgplayer-error) {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(4px);
  color: #fff;
  font-size: 16px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .xgplayer-container {
    border-radius: 4px;
  }

  :deep(.xgplayer) {
    border-radius: 4px;
  }

  :deep(.xgplayer-start) {
    width: 60px;
    height: 60px;
  }

  :deep(.xgplayer-start .xgplayer-start-img) {
    width: 24px;
    height: 24px;
  }

  :deep(.xgplayer-progress) {
    height: 4px;
  }

  :deep(.xgplayer-progress-dot) {
    width: 12px;
    height: 12px;
  }
}
</style>
<style>
.xgplayer-start {
  transform: translate(-50%, -50%) !important;
}
.xgplayer-start:hover {
  transform: translate(-50%, -50%) !important;
}
</style>
